package com.tcs.config;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcs.file.ILoadFile;
import com.tcs.model.porxypool.proxyPoolBean;
import com.tcs.util.constant.SystemConstants;

/**
 * 代理池配置
 * @author wangbo
 */
@Component(value="proxyPoolConfig")
public class ProxyPoolConfig implements IProxyPoolConfig {
	
	private final Logger logger = LoggerFactory.getLogger(ProxyPoolConfig.class);
	
	@Resource(name="loadFile")
	private ILoadFile iLoadFile;
	
	@Override
	public BufferedInputStream getConfigInputStream() {
		BufferedInputStream inputStream = null;
		try {
			File file = iLoadFile.loadFile();
			inputStream = new BufferedInputStream(new FileInputStream(file));
		} catch (IOException e) {
			logger.error("" , e);
		}
		return inputStream;
	}

	@Override
	public BufferedReader getConfigReader() {
		BufferedReader bufferedReader = null;
		try {
			File file = iLoadFile.loadFile();
			bufferedReader = new BufferedReader(new FileReader(file));
		} catch (IOException e) {
			logger.error("" , e);
		}
		return bufferedReader;
	}

	@Override
	public String getConfigPath() {
		File file = null;
		try {
			file = iLoadFile.loadFile();
		} catch (IOException e) {
			logger.error("" , e);
		}
		return file.getPath();
	}

	@Override
	public proxyPoolBean getProxyPoolModel() {
		BufferedReader bufferedReader = this.getConfigReader();
		String readLine;
		StringBuilder sb = new StringBuilder(1000);
		proxyPoolBean proxyPoolBean = null;
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			while (null != (readLine = bufferedReader.readLine())) {
				if (!readLine.contains(SystemConstants.ProxyPool.JINGHAO)) {
					sb.append(readLine.trim());
				}
			}
			proxyPoolBean = objectMapper.readValue(sb.toString(), new TypeReference<proxyPoolBean>(){});
		} catch (IOException e) {
			logger.error("" , e);
		}
		return proxyPoolBean;
	}

	@Override
	public List<proxyPoolBean> getProxyPoolList() {
		BufferedReader bufferedReader = this.getConfigReader();
		String readLine;
		StringBuilder sb = new StringBuilder(1000);
		List<proxyPoolBean> proxyPoolList = null;
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			while (null != (readLine = bufferedReader.readLine())) {
				if (!readLine.startsWith("#")) {
					sb.append(readLine.trim());
				}
			}
			proxyPoolList = objectMapper.readValue(sb.toString(), new TypeReference<proxyPoolBean>(){});
		} catch (IOException e) {
			logger.error("" , e);
		}
		return proxyPoolList;
	}
}